package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.clients.ItemClient;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import com.hmall.common.utils.UserHolder;
import com.hmall.search.mapper.SearchMapper;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.ISearchService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ISearchServiceImpl extends ServiceImpl<SearchMapper, ItemDoc> implements ISearchService {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ItemClient itemClient;

    @Override
    public List<String> getSuggestion(String prefix) {
        // 1.准备Request
        SearchRequest request = new SearchRequest("hmall");
        // 2.准备DSL
        request.source().fetchSource(new String[0], null);
        request.source().suggest(new SuggestBuilder()
                .addSuggestion(
                        "my_suggestion",
                        SuggestBuilders.completionSuggestion("suggestion")
                                .size(10)
                                .skipDuplicates(true)
                                .prefix(prefix)
                ));
        // 3.发送请求
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            // 4.1获取suggestion
            CompletionSuggestion suggestion = response.getSuggest().getSuggestion("my_suggestion");
            // 4.2获取options
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            // 4.3循环遍历，获取text
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                list.add(option.getText().string());
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("hmall");
            // 2.准备DSL
            // 2.1.查询结果不带文档数据
            request.source().size(0);
            // 2.2.设置过滤条件，创建布尔查询
            setQueryBuilderRequest(params, request);
            // 2.3 聚合条件
            request.source().aggregation(
                    AggregationBuilders.terms("brandAgg").field("brand").size(20)
            );
            request.source().aggregation(
                    AggregationBuilders.terms("categoryAgg").field("category").size(20)
            );
            // 3.发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Map<String, List<String>> map = new HashMap<>(2);
            Aggregations aggregations = response.getAggregations();
            // 4.1 根据名称获取品牌聚合
            Terms brandAgg = aggregations.get("brandAgg");
            List<String> brandList = new ArrayList<>();
            for (Terms.Bucket bucket : brandAgg.getBuckets()) {
                String keyString = bucket.getKeyAsString();
                brandList.add(keyString);
            }
            map.put("brand", brandList);
            // 4.2 根据名称获取分类聚合
            Terms categoryAgg = aggregations.get("categoryAgg");
            List<String> categoryList = new ArrayList<>();
            for (Terms.Bucket bucket : categoryAgg.getBuckets()) {
                String keyString = bucket.getKeyAsString();
                categoryList.add(keyString);
            }
            map.put("category", categoryList);

            return map;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void setQueryBuilderRequest(RequestParams params, SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 2.2.1  key
        String key = params.getKey();
        if (StringUtils.isNotBlank(key)) {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        } else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        // 2.2.2  brand
        // 2.2.3  category
        String category = params.getCategory();
        if (StringUtils.isNotBlank(category)) {
            boolQuery.filter(QueryBuilders.termQuery("category", category));
        }
        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand", brand));
        }
        // 2.2.4  price
        Long minPrice = params.getMinPrice();
        Long maxPrice = params.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                    .lte(maxPrice * 100)
                    .gte(minPrice * 100));
        }
        // 2.2.5  放入request
        String sortBy = params.getSortBy();
        // 排序规则
        FunctionScoreQueryBuilder.FilterFunctionBuilder isAD = new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                QueryBuilders.termQuery("isAD", true),
                ScoreFunctionBuilders.weightFactorFunction(100)
        );

        FunctionScoreQueryBuilder queryBuilder = QueryBuilders.functionScoreQuery(
                boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        isAD
                }
        );
        request.source().query(queryBuilder);
    }

    @Override
    public PageDTO<ItemDoc> getList(RequestParams params) {
        try {
            // 1.创建request
            SearchRequest searchRequest = new SearchRequest("hmall");
            String sortBy = params.getSortBy();
            if (sortBy.equals("price")) {
                searchRequest.source().sort("price", SortOrder.ASC);
            }
            if (sortBy.equals("sold")) {
                searchRequest.source().sort("sold", SortOrder.DESC);
            }
            // 高亮
            searchRequest.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
            // 2.准备DSL
            // 分页
            int page = params.getPage();
            int size = params.getSize();
            searchRequest.source().from((page - 1) * size).size(size);
            setQueryBuilderRequest(params, searchRequest);
            // 3.发送请求
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            // 4.解析结果
            SearchHit[] hits = response.getHits().getHits();
            List<ItemDoc> list = new ArrayList<>();

            for (SearchHit hit : hits) {
                Map<String, HighlightField> map = hit.getHighlightFields();
                String json = hit.getSourceAsString();
                ItemDoc itemDoc = JSONObject.parseObject(json, ItemDoc.class);
                if (map != null && map.size() > 0) {
                    HighlightField field = map.get("name");
                    String value = field.getFragments()[0].string();
                    itemDoc.setName(value);
                }
                list.add(itemDoc);
            }
            Long total = response.getHits().getTotalHits().value;
            return new PageDTO<ItemDoc>(total, list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void saveById(Map<String,Object> message) {
        try {
            Long itemId = (Long) message.get("id");
            Long userId = (Long) message.get("userId");
            UserHolder.setUser(userId);
            // 1.调用商品微服务查询商品数据
            Item item = itemClient.getById(itemId);
            // 2.转换为ItemDoc
            ItemDoc itemDoc = new ItemDoc(item);
            // 3.转JSON
            String json = JSON.toJSONString(itemDoc);

            // 1.准备Request
            IndexRequest request = new IndexRequest("item").id(itemDoc.getId().toString());
            // 2.准备请求参数DSL，其实就是文档的JSON字符串
            request.source(json, XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
            UserHolder.removeUser();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteById(Long id) {
        System.err.println(id);
        try {
            DeleteRequest deleteRequest = new DeleteRequest("hmall",id.toString());
            client.delete(deleteRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
